<?php
/**
 * @desc 微信.交易查询
 * @document https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&index=4
 * @author Vincent
 */

namespace young\payment;

use young\Common;

class WxQuery extends WxConfig
{
    //交易状态
    private $tradeStatus = [
        'SUCCESS' => '支付成功',
        'REFUND' => '转入退款',
        'NOTPAY' => '未支付',
        'CLOSED' => '已关闭',
        'REVOKED' => '已撤销',
        'USERPAYING' => '用户支付中',
        'PAYERROR' => '支付失败'
    ];

    public function run($data)
    {
        $this->setConfig($data['config']);
        return $this->handle($data['order_sn']);
    }

    public function handle($orderSn)
    {
        $url = 'https://api.mch.weixin.qq.com/pay/orderquery';
        $common = [];
        $common['appid'] = $this->appid;
        $common['mch_id'] = $this->mch_id;
        $common['nonce_str'] = Common::rand_string(32);
        $common['out_trade_no'] = $orderSn;
        $common['sign'] = $this->sign($common);

        $xml = Common::arrayToXml($common);
        $result = Common::request_post($url, $xml, 0);
        $data = Common::xmlToArray($result);

        if ($data['return_code'] == 'SUCCESS') {

            $verifySign = $this->verifySign($data);
            if ($verifySign === true) {
                return [
                    'error' => false,
                    'order_sn' => $data['out_trade_no'],
                    'trade_no' => $data['transaction_id'],
                    'total_amount' => $data['total_fee'],//交易总金额
                    'pay_date' => $data['time_end'],
                    'trade_status' => $this->tradeStatus[$data['trade_state']]
                ];
            } else {
                throw new \Exception('[code:-1][msg:签名失败]');
            }

        } else {
            throw new \Exception('[code:' . $data['return_code'] . '][msg:' . $data['return_msg'] . ']');
        }
    }
}